package cn.dianchiyun.protocol.netty.dtu.handler.impl;

import cn.dianchiyun.protocol.netty.consts.Const;
import cn.dianchiyun.protocol.netty.dtu.entity.Connection;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class DTUServiceHandler extends ChannelHandlerAdapter{

	private static final Logger logger = LogManager.getLogger("dtu_server");
	
	//活跃的
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}

	//channel.close 后调用
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Connection conn = ctx.channel().attr(Const.connection).get();
		if (conn == null) {
			super.channelInactive(ctx);
			return;
		}
		if(logger.isDebugEnabled()){
			logger.debug("编号为"+conn.getIdentityId()+"的设备状态为------离线。");
		}
		conn.logOut();
		super.channelInactive(ctx);
		
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.channel().close();
		super.exceptionCaught(ctx, cause);
	}
		
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("服务器发送的数据:{}", msg.toString());



		//DTUWrite dtuMsg = (DTUWrite) msg;
		
		/*if (dtuMsg.getType() == 0) {
			return ;
		}*/

		logger.debug("msg:" + msg);
		super.channelRead(ctx, msg);
	}


}
